import { getUserList, addUser, searchUserByName, updateUser, getSingleUser, deleteUser } from '@/api/user'
import { getToken } from '@/utils/auth'

const user = {
  state: {
    userList: [],
    singleItem: {},
    userListTotalItem: '',
    roken: getToken() || ''
  },
  mutations: {
    SET_LIST: (state, data) => {
      state.userList = data
    },
    SET_USER_LIST_TOTAL_ITEM: (state, data) => {
      state.userListTotalItem = data
    },
    SET_SINGLE_ITEM: (state, data) => {
      state.singleItem = data
    }
  },
  actions: {
    GetUserList: ({ commit, state }, params) => {
      return new Promise((resolve, reject) => {
        getUserList(state.token, params).then(response => {
          const data = response.data
          // console.log(data)
          if (data.rows && data.rows.length > 0) { // 验证返回的roles是否是一个非空数组
            commit('SET_LIST', data.rows)
            commit('SET_USER_LIST_TOTAL_ITEM', data.total)
          } else {
            reject('getUserlistFailed: list must be a non-null array !')
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
      })
    },
  

  AddUser: ({ state }, params) => {
    return new Promise((resolve, reject) => {
      addUser(state.token, params).then(res => {
        if (res.result === 'success') {
          resolve(res)
        } else {
          reject(res)
        }
      }).catch(err => {
        reject(err)
      })
    })
  },

  getUserByName: ({ state }, params) => {
    return new Promise((resolve, reject) => {
      searchUserByName(state.token, params).then(res => {
        if (res.result === 'success') {
          resolve(res)
        } else {
          reject(res)
        }
      }).catch(err => {
        reject(err)
      })
    })
  },

  UpdateUser: ({ state }, params) => {
    return new Promise((resolve, reject) => {
      updateUser(state.token, params).then(res => {
        if (res.result === 'success') {
          resolve(res)
        } else {
          reject(res)
        }
      }).catch(err => {
        reject(err)
      })
    })
  },

  GetSingleUser: ({ commit, state }, params) => {
    return new Promise((resolve, reject) => {
      getSingleUser(state.token, params).then(res => {
        if (res.result === 'success') {
          commit('SET_SINGLE_ITEM', res.data)
          resolve(res)
        } else {
          reject(res)
        }
      }).catch(err => {
        reject(err)
      })
    })
  },

  DeleteUser: ({ state }, params) => {
    return new Promise((resolve, reject) => {
      deleteUser(state.token, params).then(res => {
        if (res.result === 'success') {
          resolve(res)
        } else {
          reject(res)
        }
      }).catch(err => {
        reject(err)
      })
    })
  }
  },
}

export default user
